package com.lagou.config;

import org.springframework.util.CollectionUtils;

import java.util.*;

public class RandomLoadBalance extends LoadBalanse {

    @Override
    public String choseServiceHost() {
        String result = "";

        if (!CollectionUtils.isEmpty(SERVICE_LIST)) {
            //选择rpc调用耗时最小的provider来进行下次调用
            List<Long> timeList = new ArrayList<>();
            for (String ip : SERVICE_LIST) {
                Long timeUse = timeMap.get(ip);
                if (timeUse == null) {
                    timeUse = 0L;
                }
                timeList.add(timeUse);
            }
            if (timeList.get(0) > 0) {
                result = getKeyByLoop(timeMap, Collections.min(timeList));
            } else {
                int index = new Random().nextInt(SERVICE_LIST.size());
                result = SERVICE_LIST.get(index);
            }

        }
        return result;
    }

    @Override
    public void setTimeMap(String ip, Long time) {
        timeMap.put(ip, time);
    }


    private String getKeyByLoop(Map<String, Long> map, Long value) {
        for (Map.Entry<String, Long> entry : map.entrySet()) {
            System.out.println("key-" + entry.getKey() + ",value-" + entry.getValue() + "ms");
        }
        for (Map.Entry<String, Long> entry : map.entrySet()) {
            if (Objects.equals(entry.getValue(), value)) {
                return entry.getKey();
            }
        }
        return "";
    }
}
